package com.bulletelc.apollopre.module.main.center.collection;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.CollectionBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by CX on 2018/1/25.
 */

public class CollectionPresenter extends BasePresenter<CollectionContract.View> implements CollectionContract.Presenter {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getCollectionsList() {
        getCollections();
    }

    @Override
    public void removeItem(String collectionId, int position) {
        removeCollection(collectionId, position);
    }

    /**
     * 删除指定搜藏
     */
    private void removeCollection(String collectionId, final int position) {
        OkGo.<String>post(NetWorkPath.POST_USER_COLLECTION_DELETE + "?id=" + collectionId)
                .headers(NetWorkPath.HEADER_KEY_AUTH, GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseRemove(response ,position);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorRemove(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析删除结果
     * @param response
     * @param position
     */
    private void parseRemove(Response<String> response, int position) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject metaObj = object.getJSONObject("meta");
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(metaObj.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessRemove(position);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailRemove(metaObj.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorRemove("数据解析有误");
                }
            }

        } else {
            if (isViewAttached()) {
                getView().onFailRemove(response.body().toString());
            }
        }
    }


    /**
     * 获取所有收藏商品
     */
    public void getCollections() {
        OkGo.<String>get(NetWorkPath.GET_USER_COLLECTIONS)
                .headers("Authorization", GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCollections(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorCollectionsList(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解释获取结果
     * @param response
     */

    public void parseCollections(Response<String> response) {
        if(response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if(GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getName().contains("_links");
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create();
                    Type type = new TypeToken<List<CollectionBean>>(){}.getType();
                    List<CollectionBean> collects = gson.fromJson(obj.getJSONArray("data").toString(), type);
                    if(isViewAttached()) {
                        getView().onSuccessCollectionsList(collects);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailCollectionsList(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorCollectionsList("数据解析错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailCollectionsList(response.body().toString());
            }
        }
    }
}
